package com.smbms.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mysql.cj.util.StringUtils;
import com.mysql.cj.xdevapi.JsonArray;
import com.smbms.pojo.Role;
import com.smbms.pojo.User;
import com.smbms.service.RoleService;
import com.smbms.service.UserService;
import com.smbms.tools.Constants;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private RoleService roleService;

   @RequestMapping(value = "/list.html")
    public String getUserList(Model model, @RequestParam(value = "pageIndex", required = false) Integer currPageNo
            , @RequestParam(value = "queryname", required = false) String queryName
            , @RequestParam(value = "queryUserRole", required = false) Integer queryUserRole) {
        // 设置页面容量
        int pageSize = Constants.pageSize;
        //当前页码
        if (currPageNo == null) {
            currPageNo = 1;
        }
        if (queryUserRole == null) {
            queryUserRole = 0;
        }
        List<Role> roleList = roleService.getRoleList();
        IPage<User> iPageUser = userService.getUserList(queryName, queryUserRole, currPageNo, pageSize);
        List<User> userList = iPageUser.getRecords();

        int totalCount = (int) iPageUser.getTotal();
        //总页数
        int totalPageCount = (int) iPageUser.getPages();

        model.addAttribute("userList", userList);
        model.addAttribute("roleList", roleList);
        model.addAttribute("currentPageNo", currPageNo);
        model.addAttribute("totalCount", totalCount);
        model.addAttribute("totalPageCount", totalPageCount);
        return "userlist";
    }

    @GetMapping(value = "/add.html")
    public String getAdd() {
        return "useradd";
    }

    @RequestMapping(value = "/addsave.html", method = RequestMethod.POST)
    public String addSave(@Valid User user, BindingResult binBindingResult, HttpServletRequest request,
                          @RequestParam(value = "attachs", required = false) MultipartFile[] attachs) {
        if (binBindingResult.hasErrors()) {
            return "useradd";
        }

        String[] paths = new String[2];
        boolean tag = mutiFileUpload(attachs, request, paths);

        if (!tag) {
            return "useradd";
        }
        User loginUser = (User) request.getSession().getAttribute(Constants.USER_SESSION);

        user.setCreatedBy(loginUser.getId());
        user.setCreationDate(new Date());
        user.setIdPicPath(paths[0]);
        user.setWorkPicPath(paths[1]);

        boolean result = userService.add(user);

        if (result) {
            return "redirect:/user/list.html";
        }
        return "useradd";
    }

    private boolean mutiFileUpload(MultipartFile[] attachs, HttpServletRequest request, String[] paths) {
        String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");

        String errorInof = null;

        for (int i = 0; i < attachs.length; i++) {
            MultipartFile attach = attachs[i];

            if (!attach.isEmpty()) {

                if (i == 0) {
                    errorInof = "uploadFileError";
                } else {
                    errorInof = "uploadWpError";
                }

                String oldFileName = attach.getOriginalFilename();// 原文件名
                String prefix = FilenameUtils.getExtension(oldFileName);// 原文件后缀
                int filesize = 500000;
                if (attach.getSize() > filesize) {// 上传大小不得超过 500k
                    request.setAttribute(errorInof, " * 上传大小不得超过 500k");
                    return false;
                } else if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
                        || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")) {// 上传图片格式不正确

                    String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal.jpg";

                    File targetFile = new File(path, fileName);

                    if (!targetFile.exists()) {
                        targetFile.mkdirs();
                    }

                    try {
                        attach.transferTo(targetFile);
                    } catch (Exception e) {

                        e.printStackTrace();
                        request.setAttribute(errorInof, " * 上传失败！");
                        return false;
                    }
                    paths[i] = path + File.separator + fileName;
                } else {
                    request.setAttribute(errorInof, " * 上传图片格式不正确");
                    return false;
                }
            }
        }
        return true;
    }

    private String singleFileUpload(MultipartFile attach, HttpServletRequest request) {
        if (!attach.isEmpty()) {
            String path = request.getSession().getServletContext()
                    .getRealPath("statics" + File.separator + "uploadfiles");
            String oldFileName = attach.getOriginalFilename();// 原文件名
            String prefix = FilenameUtils.getExtension(oldFileName);// 原文件后缀
            int filesize = 500000;
            if (attach.getSize() > filesize) {// 上传大小不得超过 500k
                request.setAttribute("uploadFileError", " * 上传大小不得超过 500k");
                return "error";
            } else if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
                    || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")) {// 上传图片格式不正确

                String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal.jpg";

                File targetFile = new File(path, fileName);

                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                }

                try {
                    attach.transferTo(targetFile);
                } catch (Exception e) {

                    e.printStackTrace();
                    request.setAttribute("uploadFileError", " * 上传失败！");
                    return "error";
                }

                return path + File.separator + fileName;
            } else {
                request.setAttribute("uploadFileError", " * 上传图片格式不正确");
                return "error";
            }

        }
        return null;
    }

    @RequestMapping(value = "/usermodify.html", method = RequestMethod.GET)
    public String getUserById(@RequestParam String uid, Model model) {
        User user = userService.getUserById(uid);
        model.addAttribute(user);
        return "usermodify";
    }

    @RequestMapping(value = "/usermodifysave.html", method = RequestMethod.POST)
    public String modifyUserSave(User user, HttpSession session) {
        user.setModifyBy(((User) session.getAttribute(Constants.USER_SESSION)).getId());
        user.setModifyDate(new Date());
        if (userService.modify(user)) {
            return "redirect:/user/list.html";
        }
        return "usermodify";
    }

    @GetMapping(value = "/view")
    @ResponseBody
    public User view(@RequestParam String id) {
        User user = new User();
        try {
            user = userService.getUserById(id);
        } catch (Exception e) {

            e.printStackTrace();
        }
        return user;
    }

    @RequestMapping(value = "/user.do", method = RequestMethod.GET)
    @ResponseBody
    public Object user() {
        List<Role> roles = roleService.getRoleList();
        return roles;
    }

    @RequestMapping(value = "/ucexist.html")
    @ResponseBody
    public Object userCodeIsExit(@RequestParam String userCode) {
        HashMap<String, String> resultMap = new HashMap<>();
        if (StringUtils.isNullOrEmpty(userCode)) {
            resultMap.put("userCode", "exist");
        } else {
            User user = userService.selectUserCodeExist(userCode);
            if (null != user)
                resultMap.put("userCode", "exist");
            else
                resultMap.put("userCode", "noexist");
        }
        return resultMap;
    }

    @RequestMapping(value = "/deluser", method = RequestMethod.GET)
    @ResponseBody
    public Object del(@RequestParam String delId) {
        HashMap<String, Object> resultMap = new HashMap<>();
        if (StringUtils.isNullOrEmpty(delId)) {
            resultMap.put("delResult", "notexist");
        } else {
            boolean result = userService.deleteUserById(Integer.parseInt(delId));
            if (result) {
                resultMap.put("delResult", result);
            } else {
                resultMap.put("delResult", result);
            }
        }
        return resultMap;
    }
}
